<template>
  <div class="container">
    <a-space direction="vertical" :size="16" style="display: block">
      <a-row style="margin-bottom: 16px" :gutter="16">
        <a-col :span="2">
          <a-list style="background-color: white">
            <a-list-item
              v-for="item in weixinStore.wxList"
              :key="item.wxid"
              @click="handle(item)"
              :style="{
                backgroundColor:
                  currentWxid === item.wxid ? '#FFFCE8' : 'white',
              }"
            >
              <a-list-item-meta>
                <template #avatar>
                  <a-avatar>
                    <img alt="avatar" :src="item.avatarUrl" />
                  </a-avatar>
                </template>
              </a-list-item-meta>
              <template #actions>
                <icon-caret-right
                  :style="{
                    color: currentWxid === item.wxid ? '#F53F3F' : '',
                  }"
                />
              </template>
            </a-list-item>
          </a-list>
        </a-col>
        <a-col :span="22">
          <a-card>
            <!-- 会员费用配置 -->
            <template #title>
              <a-row :gutter="24" style="margin-top: 10px">
                <a-col :span="6"> 会员费用配置 </a-col>
                <a-col :span="6">
                  <a-typography-paragraph
                    editable
                    v-model:editText="monthPrice"
                    @edit-end="handleEditVip('month', monthPrice)"
                  >
                    30天：￥{{ monthPrice }}元
                  </a-typography-paragraph>
                </a-col>
                <a-col :span="6">
                  <a-typography-paragraph
                    editable
                    v-model:editText="quarterPrice"
                    @edit-end="handleEditVip('quarter', quarterPrice)"
                  >
                    90天：￥{{ quarterPrice }}元
                  </a-typography-paragraph>
                </a-col>
                <a-col :span="6">
                  <a-typography-paragraph
                    editable
                    v-model:editText="yearPrice"
                    @edit-end="handleEditVip('year', yearPrice)"
                  >
                    365天：{{ yearPrice }}元
                  </a-typography-paragraph>
                </a-col>
              </a-row>
            </template>
            <a-table
              row-key="wxid"
              :data="friendList"
              :columns="columns"
              :loading="loading"
              :pagination="{
                total: count,
                current: current,
                pageSize: pageSize,
                showTotal: true,
                showPageSize: true,
              }"
              :row-selection="{
                type: 'checkbox',
                showCheckedAll: true,
                onlyCurrent: false,
              }"
              v-model:selectedKeys="selectedKeys"
              @page-change="handlePageChange"
              @page-size-change="handlePageSizeChange"
            >
              <template #wxinfo="{ record }">
                <a-row>
                  <a-col :span="6" style="text-align: center"
                    ><a-avatar :trigger-icon-style="{ color: '#3491FA' }">
                      <img alt="avatar" :src="record.avatarMinUrl" />
                      <template #trigger-icon>
                        <div v-if="record.sex"><icon-woman /></div
                        ><div v-else><icon-man /></div>
                      </template>
                    </a-avatar>
                  </a-col>
                  <a-col :span="18">
                    <div>昵称：{{ record.nick }} </div>
                    <div>微信号：{{ record.wxNum }}</div>
                    <div>手机号：{{ record.phome }}</div>
                  </a-col>
                </a-row>
              </template>
              <template #action="{ record }">
                <a-button @click="handleAccount(record._id, record.wxid)">财务明细</a-button>
                <a-button @click="handleAccount(record._id, record.wxid)">人工续费</a-button>
              </template>
            </a-table>
          </a-card>
        </a-col>
      </a-row>
    </a-space>
  </div>

  <a-drawer
  :width="300"
    :visible="drawerVisible"
    :hide-cancel="true"
    ok-text="关闭"
    @ok="handleOk"
    @cancel="handleCancel"
    unmountOnClose
  >
    <Account :ownerWxid="currentWxid" :wxid="friendwxid" ></Account>
  </a-drawer>
</template>

<script lang="ts" setup>
  import { ref, onMounted } from 'vue';
  import { useWeixinStore } from '@/store';
  import { Message, TableColumnData } from '@arco-design/web-vue';
  import { getFriendList, enableVip, editVip } from '@/api/weixin';
  import Account from './components/account.vue';

  const weixinStore = useWeixinStore();
  const currentWxid = ref('');
  const currentAvatar = ref('');
  const friendwxid = ref('');

  const current = ref(1);
  const pageSize = ref(10);
  const count = ref(0);
  const loading = ref(false);
  const friendList = ref([]);
  const selectedKeys = ref<string[]>([]);
  const drawerVisible = ref(false);

  // 搜索表单数据
  const searchForm = ref({
    nick: '',
    phone: '',
    tags: '',
  });

  const columns: TableColumnData[] = [
    {
      title: '基本信息',
      slotName: 'wxinfo',
      width: 250,
    },
    {
      title: '微信号',
      dataIndex: 'wxid',
      width: 150,
    },
    {
      title: '会员有效期',
      dataIndex: 'vipExpireTime',
      width: 200,
    },
    {
      title: '操作',
      slotName: 'action',
      width: 200,
    },
  ];

  // 获取好友列表数据
  const fetchFriendList = async (wxid: string) => {
    loading.value = true;
    try {
      const res: any = await getFriendList(wxid, {
        field: {
          nick: searchForm.value.nick,
          phone: searchForm.value.phone,
          tags: searchForm.value.tags,
          isvip: true,
        },
        page: current.value,
        pageSize: pageSize.value,
      });
      if (res.code === 20000) {
        count.value = res.data.count;
        friendList.value = res.data.list;
      } else {
        Message.error(res.msg || '获取好友列表失败');
      }
    } catch (error) {
      console.error('获取好友列表失败:', error);
    } finally {
      loading.value = false;
    }
  };

  // 处理页码变化
  const handlePageChange = async (page: number) => {
    current.value = page;
    await fetchFriendList(currentWxid.value);
  };
  // 处理每页条数变化
  const handlePageSizeChange = async (size: number) => {
    pageSize.value = size;
    current.value = 1; // 切换页面大小时重置为第一页
    await fetchFriendList(currentWxid.value);
  };
  // 搜索处理
  const handleSearch = () => {
    current.value = 1; // 重置页码
    fetchFriendList(currentWxid.value);
  };

  // 重置搜索
  const handleReset = () => {
    searchForm.value = {
      nick: '',
      phone: '',
      tags: '',
    };
    current.value = 1;
    fetchFriendList(currentWxid.value);
  };
  // 开启vip
  const monthPrice = ref(0);
  const quarterPrice = ref(0);
  const yearPrice = ref(0);
  const isopenvip = ref(false);
  const handleOpenVip = async () => {
    try {
      const res: any = await enableVip({
        wxid: currentWxid.value,
      });
      if (res.code === 20000) {
        isopenvip.value = true;
        monthPrice.value = res.data.month;
        quarterPrice.value = res.data.quarter;
        yearPrice.value = res.data.year;
      } else {
        Message.error(res.msg || '获取失败');
      }
    } catch (error) {
      console.error('获取失败:', error);
    } finally {
      loading.value = false;
    }
  };

  const handleEditVip = async (field: string, value: number) => {
    try {
      const res: any = await editVip({
        wxid: currentWxid.value,
        field,
        value: Number(value),
      });
      if (res.code === 20000) {
        Message.info('修改成功');
        isopenvip.value = true;
        monthPrice.value = res.data.month;
        quarterPrice.value = res.data.quarter;
        yearPrice.value = res.data.year;
      } else {
        Message.error(res.msg || '修改失败');
      }
    } catch (error) {
      console.error('修改失败:', error);
    } finally {
      loading.value = false;
    }
  };
  const handleAccount = (id: string, wxid: string) => {
    drawerVisible.value = true;
    friendwxid.value = wxid
  };
  const handleOk = () => {
    drawerVisible.value = false;
  };
  const handleCancel = () => {
    drawerVisible.value = false;
  };

  onMounted(async () => {
    await weixinStore.fetchWxList();
    // 如果有微信列表数据，默认选中第一个
    if (weixinStore.wxList.length > 0) {
      const defaultWxid = weixinStore.wxList[0].wxid;
      currentWxid.value = defaultWxid;
      currentAvatar.value = weixinStore.wxList[0].avatarUrl;
      await fetchFriendList(defaultWxid);
      await handleOpenVip();
    }
  });

  // 选择微信账号
  const handle = (record: any) => {
    currentWxid.value = record.wxid;
    currentAvatar.value = record.avatarUrl;
    weixinStore.setSelectedWeixin(record.wxid, record.avatarUrl);
  };
</script>

<style scoped>
  .container {
    padding: 16px;
  }
</style>
